package com.fitns.user.service.pub;

import com.fitns.user.constant.Constants;
import com.fitns.user.utils.UuidUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Service
public class FileService {
    public String IoReadImage(String imgName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletOutputStream out= null;
        FileInputStream ips =null;
        try{
//获取图片存放路径
            String imgPath=Constants.IMAGE_PATH +imgName;
            ips=new FileInputStream(new File(imgPath));
            response.setContentType("multipart/form-data");
            out =response.getOutputStream();
//读取文件流
            int len = 0;
            byte[] buffer=new byte[1024*10];
            while((len=ips.read(buffer))!=-1){
                out.write(buffer,0,len);
            }
            out.flush();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            out.close();
            ips.close();
        }
        return null;
    }

    public String uploadImage(MultipartFile pic) throws Exception {
        // 把图片保存到图片目录下
        // 为每个文件生成一个新的文件名
        String picName = UuidUtils.getUUID();
        // 取文件扩展名
        String oriName = pic.getOriginalFilename();
        String extName = oriName.substring(oriName.lastIndexOf("."));
        // 保存文件
        pic.transferTo(new File(Constants.IMAGE_PATH + picName + extName));
        return picName + extName;
    }

}
